import request from './request';
// import setOptions from './setOptions';
import { getModelByCode } from './modelManageService';
import { getDvaApp } from 'umi';

const devUrl = window.appcfg._servicesUrl;
// const devUrl = 'http://dev.arcgisonline.cn/wxtc-service';

const thridPartUrl = `http://wccg.tech:88/api`;
const newThridPartUrl = `http://wccg.tech:82/api`;

// const userManageUrl = 'http://120.195.199.66:12343';
const userManageUrlProxy = 'https://portal.wccg.tech:9002/weather'; // 直接调用用户信息api会跨域，借用天气服务转发一下
let userManageToken = '';

// async function getUserManageToken() {
//   if (!userManageToken) {
//     const { data } = await request('/door_query/getToken', {
//       // const { data } = await request(userManageUrl + '/door_query/getToken', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/json',
//       },
//       body: JSON.stringify({
//         appid: 'sys1r2AROwVZvNzAB20',
//         secret: 'b1XSSCC1OC3cAMXX',
//       }),
//     });
//     userManageToken = data.data;
//   }
//   return userManageToken;
// }

export async function getAllWorkers(itemId) {
  const data = await request(`${userManageUrlProxy}/door_query/allWorkers?itemId=${itemId}`, {
    // const data = await request(`${userManageUrl}/door_query/allWorkers?itemId=${itemId}`, {
    // headers: {
    //   token: await getUserManageToken(),
    // },
  });
  return data;
}

export async function queryInAndOutByPeopleAndDay(itemId, dateStr = '2021-06-01') {
  const data = await request(
    `${userManageUrlProxy}/door_query/queryInAndOutByPeopleAndDay?itemId=${itemId}&stTm=${dateStr}`,
    // `${userManageUrl}/door_query/queryInAndOutByPeopleAndDay?itemId=${itemId}&stTm=${dateStr}`,
    // {
    //   headers: {
    //     token: await getUserManageToken(),
    //   },
    // },
  );
  return data;
}

export function getUsername() {
  let userName = 'test';
  try {
    let _userName = getDvaApp()._store.getState().app.userName || '';
    if (_userName) {
      userName = _userName;
    }
  } catch (error) {
    console.warn('-------------获取用户名失败', getDvaApp()._models);
    alert('-------------获取用户名失败');
  }
  return userName;
}

// 获取所有的模型信息
export function getBimMenuTree(code) {
  if (!code) {
    console.error('需要填写模型code');
    return;
  }
  return getModelByCode(code);
}

// // 获取所有的模型信息 V2
// export function getBimMenuTree() {
//   const options = setOptions('GET');
//   return request(window.appcfg.servicesUrl + '/bMenu/getTree', options);
// }

// // 获取所有的模型信息
// export function getBimType() {
//   const options = setOptions('GET');
//   return request(window.appcfg.servicesUrl + '/property/getBimType', options);
// }

// // 对比两个模型的构件
// export function getDifference(param) {
//   const options = setOptions('POST', param);
//   return request(window.appcfg.servicesUrl + '/slpk/getDifference', options);
// }

// todo 跨域
// 获取building类型的属性和属性值
export function getBuildingAttributes(url) {
  return request(url + '/layers/0/statistics/summary?f=json', { method: 'GET' });
}

export function getBuildingStatus(projectId) {
  // acceptStatus : 1 已开始 2 未开始 3 已完成
  return request(
    thridPartUrl + `/wuxi/api/project/quality/detail?projectId=${projectId}&acceptStatus=2`,
    { method: 'GET' },
  ).then(({ data }) => {
    return data.data.map(({ wbsCode }) => {
      return wbsCode;
    });
  });
}

// 分项工程总体产值计划数据
export function listSectionProgress(projectId) {
  return request(
    thridPartUrl + `/wuxi/api/project/section/productValue?projectId=${projectId}`,
  ).then(({ data }) => {
    return data.data;
  });
}
// 项目总体产值计划数据
export function listTotalProgress(projectId) {
  return request(thridPartUrl + `/wuxi/api/project/total/productValue?projectId=${projectId}`).then(
    ({ data }) => {
      return data.data;
    },
  );
}

// 工序验收详情
export function qualityAccept(projectId, wbsCode) {
  return request(
    thridPartUrl +
      `/wuxi/api/project/qualityAccept/process?projectId=${projectId}&wbsCode=${wbsCode}`,
  ).then(({ data }) => {
    return data.data;
  });
}

// 项目所有wbs的状态 用于筛选展示
export function listAllWbsIntoStatus(projectId) {
  return request(
    thridPartUrl + `/wuxi/api/project/project/allWbs/status?projectId=${projectId}`,
  ).then(({ data }) => {
    return data.data;
  });
}

// 工序验收、质量巡查、安全问题统计信息
export function taskInspectStatistics(projectId) {
  return request(
    thridPartUrl + `/wuxi/api/project/project/allWbs/taskInspect?projectId=${projectId}`,
  ).then(({ data }) => {
    if (data) {
      return data.data;
    }
    return null;
  });
}

// 所有运行项目的安全生产指数
export function listAllSafetyIndex() {
  return request(newThridPartUrl + `/wuxi/api/majorProject/getSafeIndex?emphasisFlag=1`).then(
    ({ data }) => {
      // return request(thridPartUrl + `/wuxi/api/project/project/all/safeIndex`).then(({ data }) => {
      return data.data.sectionProjectInfo;
    },
  );
}
// 某一个项目30天的安全生产指数
export function listSafetyIndexById(projectId) {
  return request(
    thridPartUrl + `/wuxi/api/project/project/oneMonth/safeIndex?projectId=${projectId}`,
  ).then(({ data }) => {
    return data.data;
  });
}

// wbs质量验收 又称 工序验收
export function getQualityProcessAccept(wbsCode) {
  return request(
    thridPartUrl + `/wuxi/api/project/project/wbs/qualityProcessAccept?wbsCode=${wbsCode}`,
  ).then(({ data }) => {
    return (data && data.data) || null;
  });
}
// wbs工程进度
export function getSingleWbsStatus(wbsCode) {
  return request(
    thridPartUrl + `/wuxi/api/project/project/singleWbs/status?wbsCode=${wbsCode}`,
  ).then(({ data }) => {
    return data.data;
  });
}

// wbs质量问题
export function getQualityInspect(id) {
  return request(thridPartUrl + `/wuxi/api/project/project/wbs/qualityInspect?id=${id}`).then(
    ({ data }) => {
      return data.data;
    },
  );
}

// wbs安全问题
export function getSafetyInspect(id) {
  return request(thridPartUrl + `/wuxi/api/project/project/wbs/safetyInspect?id=${id}`).then(
    ({ data }) => {
      return data.data;
    },
  );
}
// wbs一周类的安全巡检坐标点
export function getDangerSourceExamine(projectId) {
  return request(
    thridPartUrl + `/wuxi/api/project/project/weekly/dangerSourceExamine?projectId=${projectId}`,
  ).then(({ data }) => {
    let result = [];
    if (data.data) {
      console.log(data.data);
      result = data.data.reduce((r, { wbsCode, locationList }) => {
        const _locationList = locationList.reduce((_r, item) => {
          if (!_r[item.belongDateString]) {
            _r[item.belongDateString] = [];
          }
          _r[item.belongDateString].push(item);
          return _r;
        }, {});
        r.push({
          wbsCode,
          locationList: Object.keys(_locationList).map(key => _locationList[key]),
        });
        return r;
      }, []);
      console.log(result);
    }
    return result;
    // return data.data;
  });
}

// 所有项目产值信息
export function getProduceValueAndCalculate() {
  return request(
    // newThridPartUrl + `/wuxi/api/project/allProject/produceValueAndCalculate`,
    newThridPartUrl + `/wuxi/api/project/allProject/produceValueAndCalculate?emphasisFlag=1`,
  ).then(
    // return request(thridPartUrl + `/wuxi/api/project/allProject/produceValueAndCalculate`).then(
    ({ data }) => {
      return data.data;
    },
  );
}

// 项目的机械设备信息
export function getAllEquipments(projectId) {
  return request(thridPartUrl + `/wuxi/api/project/project/equipments?projectId=${projectId}`).then(
    ({ data }) => {
      return data.data;
    },
  );
}

// 水泥混凝土数据
export function cementConcreteProduceData(projectId) {
  return request(
    thridPartUrl + `/wuxi/api/project/cementConcreteProduceData?projectId=${projectId}`,
  ).then(({ data }) => {
    return (data && data.data) || [];
  });
}
// 货车数据
export function transportVehicleTrackData(projectId) {
  return request(
    thridPartUrl + `/wuxi/api/project/transportVehicleTrackData?projectId=${projectId}`,
  ).then(({ data }) => {
    let result = {};
    if (data && data.data) {
      result = data.data.reduce((r, e) => {
        if (!r[e.xt]) {
          r[e.xt] = {
            rawData: [],
            paths: [],
          };
        }
        r[e.xt].rawData.push(e);
        r[e.xt].paths.push([+e.jd, +e.wd]);
        return r;
      }, {});
    }
    return result;
  });
}
// 地磅数据
export function weighBridgeData(projectId) {
  return request(thridPartUrl + `/wuxi/api/project/weighBridgeData?projectId=${projectId}`).then(
    ({ data }) => {
      return (data && data.data) || [];
    },
  );
}

// gltf模型相关
export function getGltfModels() {
  // getDvaApp()
  return request(devUrl + '/api/gltf-models', {
    method: 'GET',
    headers: {
      userName: 'test',
      // userName: getUsername(),
    },
  });
}

export function deleteGltfModels(ids = []) {
  // getDvaApp()
  return request(devUrl + '/api/gltf-models', {
    method: 'DELETE',
    headers: {
      userName: getUsername(),
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(ids),
  });
}

// 用户标绘存储
export function getPlotLayers(projectId) {
  return request(`${devUrl}/api/plot-layers?projectId=${projectId}`, {
    method: 'GET',
    headers: {
      userName: getUsername(),
    },
  });
}

export function addPlotLayers({ description, graphics, layerId, layerName, projectId }) {
  return request(`${devUrl}/api/plot-layers`, {
    method: 'POST',
    headers: {
      userName: getUsername(),
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      description,
      graphics,
      layerId,
      layerName,
      projectId,
    }),
  });
}

export function updatePlotLayers({
  description,
  graphics,
  // layerId,
  id,
  layerName,
  // projectId
}) {
  return request(`${devUrl}/api/plot-layers`, {
    method: 'PUT',
    headers: {
      userName: getUsername(),
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      description,
      graphics,
      layerName,
      id,
    }),
  });
}

export function deletePlotLayers(ids = []) {
  return request(`${devUrl}/api/plot-layers`, {
    method: 'DELETE',
    headers: {
      userName: getUsername(),
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(ids),
  });
}
